package com.ihelp.rest.mis.users.service;

import java.text.DecimalFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ihelp.rest.base.po.SysCode;
import com.ihelp.rest.mis.pojo.Users;
import com.ihelp.rest.mis.users.dao.UsersDao;
import com.ihelp.rest.utils.DateUtil;
import com.ihelp.rest.utils.JsonCommon;

/**
 * 会员服务
*      
* 类名称：UsersService   
* 类描述：     
* 创建时间：2013-3-21 下午02:35:38    
* 备注：   
* @version
 */
@Service
public class UsersService {

	@Autowired
	private UsersDao usersDao;
	
	/**
	 * 会员列表JSON数据
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public String findUsersPage(int start, int pageSize) {
		return JsonCommon.getGridJson(this.usersDao.page(null, start, pageSize)).toString();
	}
	
	/**
	 * 获取单个会员
	 * @param id
	 * @return
	 */
	public Users getUsers(String id){
		if(StringUtils.isBlank(id)){
			return null;
		}
		return this.usersDao.get(id);
	}
	
	/**
	 * 保存会员
	 * @param users
	 * @return
	 */
	public String addUsers(Users users) {
		String time = DateUtil.date2String(new Date());
		String tmpCode = users.getCounty();
		String userCode = "";
		if (StringUtils.isBlank(users.getId())) {	
			// 第一次保存, AJAX提交form UUID未空串
			users.setId(null);
			users.setAddTime(time);
			users.setLastTime(time);
			userCode = getUserCode(tmpCode);
			users.setCode(userCode);
		}
		else{
			//更新时间
			users.setLastTime(time);
			if(!users.getCode().contains(tmpCode)){
				//省、市、县变动更改
				userCode = getUserCode(tmpCode);
				users.setCode(userCode);
				//users.setCode(tmpCode + users.getCode().substring(6));
			}
		}
		this.usersDao.saveOrUpdate(users);
		return SysCode.SUCCESS;
	}
	
	private String getUserCode(String adcode){
		Users u = this.usersDao.queryMaxCode(adcode);
		if(u == null){
			adcode += "000001";
		}
		else{
			String uCode = u.getCode();
			if(uCode != null && uCode.length() > 6){
				Integer intHao = Integer.parseInt(uCode.substring(6)); 
			    intHao++; 
			    DecimalFormat df = new DecimalFormat("000000"); 
			    adcode +=  df.format(intHao); 
			}
		}
		return adcode;
	}
	
	public Users getUsersByCode(String usercode){
		return this.usersDao.queryUsersByCode(usercode);
	}
	
}
